// src/utils/speech-recognition.js
import CryptoJS from 'crypto-js'
import IFlyTekConfig from '@/util/iflytek'

// 自定义URL解析函数（兼容小程序）
function parseUrl(url) {
  if (!url) return { host: '', pathname: '' };
  
  const protocolPos = url.indexOf('://');
  const hostStart = protocolPos === -1 ? 0 : protocolPos + 3;
  const pathStart = url.indexOf('/', hostStart);
  
  return {
    host: pathStart === -1 
      ? url.substring(hostStart) 
      : url.substring(hostStart, pathStart),
    pathname: pathStart === -1 
      ? '/' 
      : url.substring(pathStart)
  };
}

// 生成签名
export function generateSignature() {
  const date = new Date().toUTCString();
  const { host, pathname } = parseUrl(IFlyTekConfig.HOST);
  const signatureOrigin = `host: ${host}\ndate: ${date}\nPOST ${pathname} HTTP/1.1`;
  
  const signatureSha = CryptoJS.HmacSHA256(signatureOrigin, IFlyTekConfig.API_SECRET);
  const signature = CryptoJS.enc.Base64.stringify(signatureSha);
  
  return `api_key="${IFlyTekConfig.API_KEY}", algorithm="hmac-sha256", headers="host date request-line", signature="${signature}"`;
}

// 处理音频数据
export function processAudioData(audioData) {
  if (typeof audioData === 'string') {
    return audioData.replace(/^data:.+?;base64,/, '');
  } else if (audioData.tempFilePath && audioData.data) {
    return audioData.data;
  } else if (audioData instanceof ArrayBuffer) {
    return arrayBufferToBase64(audioData);
  } else {
    throw new Error('不支持的音频格式');
  }
}

// ArrayBuffer转Base64
function arrayBufferToBase64(buffer) {
  if (typeof wx !== 'undefined' && wx.arrayBufferToBase64) {
    return wx.arrayBufferToBase64(buffer);
  }
  
  const bytes = new Uint8Array(buffer);
  let binary = '';
  for (let i = 0; i < bytes.byteLength; i++) {
    binary += String.fromCharCode(bytes[i]);
  }
  
  // 浏览器环境使用btoa
  return typeof btoa === 'function' 
    ? btoa(binary) 
    : Buffer.from(binary).toString('base64');
}

// 语音识别主函数（重点修复）
export async function recognizeAudio(audioData) {
  try {
    const authHeader = generateSignature();
    const { host } = parseUrl(IFlyTekConfig.HOST);
    const pureBase64 = processAudioData(audioData);
    
    // 正确的请求数据结构
    const requestData = {
      common: { app_id: IFlyTekConfig.APPID },
      business: {
        language: 'zh_cn',
        domain: 'iat',
        accent: 'mandarin',
        vad_eos: 2000
      },
      data: {
        status: 2,
        format: 'audio/L16;rate=16000',  // 必须是PCM格式
        encoding: 'base64',
        audio: pureBase64
      }
    };
    
    console.log('准备发送请求', {
      host: host,
      authHeader: authHeader,
      dataLength: pureBase64.length
    });
    
    const response = await uni.request({
      url: IFlyTekConfig.HOST,
      method: 'POST',
      timeout: 10000,
      header: {
        'Content-Type': 'application/json',
        'Authorization': authHeader,
        'Host': host
      },
      data: requestData
    });
    
    // 处理响应
    const res = response[1]?.data || response?.data || response;
    console.log('API响应', res);
    
    // 验证响应格式
    if (res.code !== 0) {
      const errorMsg = res.desc || res.message || `API错误 (${res.code})`;
      throw new Error(errorMsg);
    }
    
    if (!res.data || !res.data.result) {
      throw new Error('无效的API响应结构');
    }
    
    // 提取识别结果
    return res.data.result.ws
      .map(item => (item.cw || [])
        .map(c => c.w)
        .join(''))
      .join('');
    
  } catch (error) {
    console.error('识别请求失败', {
      message: error.message,
      code: error.errCode,
      data: error?.data
    });
    
    // 细化错误类型
    if (error.errMsg?.includes('timeout')) {
      throw new Error('请求超时，请重试');
    } else if (error.errMsg?.includes('network')) {
      throw new Error('网络连接失败');
    } else if (error.message.includes('音频')) {
      throw new Error('音频格式不兼容');
    }
    
    throw new Error(`识别失败: ${error.message}`);
  }
}